// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using iPanel.DataProvider;
using Microsoft.AspNetCore.Mvc;
using OpenTelemetry.Proto.Collector.Resources.V1;

namespace iPanel.Otlp.Grpc;

[Authorize(Policy = OtlpAuthorization.PolicyName)]
[SkipStatusCodePages]
public class OtlpGrpcResourceService : OpenTelemetry.Proto.Collector.Resources.V1.ResourceService.ResourceServiceBase
{
    private readonly OtlpResourceService resourceService;
    private readonly TelemetryDbContext telemetryDbContext;

    public OtlpGrpcResourceService(OtlpResourceService resourceService, TelemetryDbContext telemetryDbContext)
    {
        this.resourceService = resourceService;
        this.telemetryDbContext = telemetryDbContext;
    }

    public override Task<ExportResponse> Export(ExportRequest request, ServerCallContext context)
    {
        return Task.FromResult(resourceService.Export(request));
    }

    public override Task<ApplyInstanceId> GetOrCreateServiceInstanceId(ApplyInstanceId request, ServerCallContext context)
    {
        var application = telemetryDbContext.Db
           .Queryable<OtlpNodeMapApplicationEntity>()
           .Where(_ => _.NodeId == request.Val)
           .First();

        if (application is null)
            lock (telemetryDbContext.Db)
            {
                application = telemetryDbContext.Db
                       .Queryable<OtlpNodeMapApplicationEntity>()
                       .Where(_ => _.NodeId == request.Val)
                       .First();
                if (application is null)
                {
                    application = new OtlpNodeMapApplicationEntity
                    {
                        Id = Guid.NewGuid(),
                        NodeId = request.Val
                    };
                    telemetryDbContext.Db.Insertable(application).ExecuteCommand();
                }
            }
        return Task.FromResult(new ApplyInstanceId
        {
            Val = resourceService.GetOrCreateServiceInstanceId(request.Val).ToString()
        });
    }
}
